package cn.org.itool.ws.framework.netty;

import cn.org.itool.ws.framework.netty.channel.WsServerInitializer;
import cn.org.itool.ws.framework.utils.ChannelGroupUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class NettyServer{

    private final int port;

    private ChannelFuture f;

    EventLoopGroup bossGroup;

    EventLoopGroup workerGroup;

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() {
        try {
            bossGroup = new NioEventLoopGroup(); // (1)
            workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap(); // (2)
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class) // (3)
                        .childHandler(new WsServerInitializer())
                        .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                        .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

                // Bind and start to accept incoming connections.
                f = b.bind(port).sync(); // (7)

                // Wait until the server socket is closed.
                // In this example, this does not happen, but you can do that to gracefully
                // shut down your server.

            } finally {

            }
        }catch (Exception e) {
            log.error("netty run error \n", e);
        }
    }

    public void stop() throws Exception {
        log.info("netty stop");
        log.info("-f stop------------------------------------");
        if (f != null) {
            f.channel().close().sync();
        }

        // 主动关闭所有连接
        ChannelGroupUtil.closeAll();

        log.info("-bossGroup stop----------------------------");
        if (bossGroup != null) {
            bossGroup.shutdownGracefully().sync();
        }

        log.info("-workerGroup stop--------------------------");
        if (workerGroup != null) {
            workerGroup.shutdownGracefully().sync();
        }


    }
}
